import { getDict } from "~/utils";
import { downloadBlob } from "@/utils";
import { downloadPost } from "../../../api/check-in.js";
import {
	addInspectionMethod,
	getInspectionItems,
	getInspectionMethod,
	delInspectionMethod,
	editInspectionMethod,
	getTinspectionName
} from "../../../api/method.js";

export default {
	provide() {
		return {
			initList: this.getListData
		};
	},
	data() {
		return {
			title: "",
			formLabelWidth: "120px",
			//检查方法列表
			tableData: [],
			propertyTypes: [],
			dialogVisible: false,
			// 物业项列表
			treeList: [],
			//搜索表单数据
			searchDataFrom: {},
			//勾选列表
			selectDataArr: [],
			unfold: false,
			restaurants: [],
			// 右侧表格请求传参
			params: {
				current: 1,
				size: 20,
				inspectionName: "",
				inspectionId: ""
			},
			// 右侧表格分页
			pager: {
				total: 0, // 总页数
				current: 1, // 当前页数
				size: 20 // 每页显示多少条
			},
			rules: {
				sort: [
					{
						required: true,
						message: "请输入排序",
						trigger: "blur"
					}
				],
				projectType: [
					{
						required: true,
						message: "请选择物业类型",
						trigger: "blur"
					}
				],
				inspectionName: [
					{
						required: true,
						message: "请输入检查项名称",
						trigger: "blur"
					}
				],
				inspectionWay: [
					{
						required: true,
						message: "请输入检查方法",
						trigger: "blur"
					}
				]
			},
			// 过滤检索配置
			filterList: [
				{
					label: "物业类型",
					inputType: "dict",
					name: "projectType",
					dictName: "property_types",
					multiple: true
				}
			],
			// 弹窗表单设置
			form: {
				inspectionWay: "",
				inspectionName: "",
				projectType: "",
				sort: null,
				remarks: "",
				inspectionId: ""
			}
		};
	},
	mounted() {
		//获取物业类型（字典）
		this.propertyTypes = getDict("property_types");
		this.getInspectionItems();
		this.getListData();
	},
	methods: {
		// 重置方法回调
		handleReset() {
			this.params.inspectionId = "";
			this.$refs.treeBox.setCurrentKey();
		},
		// 菜单点击监听
		handleMenuClick(type) {
			switch (type) {
				case "add":
					this.showAddOrEdit("add");
					break;
				case "delete":
					this.handleDelete();
					break;
				case "export":
					this.exportTable();
					break;
			}
		},
		// 全部展开
		unFoldAll() {
			this.unfold = !this.unfold;
			// 将没有转换成树的原数据
			this.treeList.forEach((e, i) => {
				this.$refs.treeBox.store.nodesMap[
					this.treeList[i].id
				].expanded = this.unfold;
			});
		},
		// 树型结构组件渲染数据模板
		renderContent(h, { node, data, store }) {
			return (
				<span class="custom-tree-node">
					<span>
						<span>{data.label}</span>
						<span> {!data.projectType ? `(${data.total})` : ""}</span>
					</span>
				</span>
			);
		},
		//导出
		exportTable() {
			if (this.tableData.length == 0) {
				if (this.params.projectType) {
					if (this.params.inspectionId)
						return this.$message({
							message: " 当前物业类型下检查项暂无可导出数据",
							type: "warning"
						});
					else
						return this.$message({
							message: "当前物业类型暂无可导出数据",
							type: "warning"
						});
				} else {
					this.$message({
						message: "暂无可导出数据",
						type: "warning"
					});
					return;
				}
			}
			var time = new Date();
			var name =
				time.getFullYear() +
				"-" +
				(time.getMonth() + 1) +
				"-" +
				time.getDate() +
				" " +
				time.getHours() +
				":" +
				time.getMinutes() +
				":" +
				time.getSeconds() +
				"检查方法列表.xlsx";
			var url = "/api/inspectionway/exportInspectionWays";
			downloadPost(url, {
				wayIds: this.selectDataArr.map(e => e.wayId),
				inspectionId: this.params.inspectionId,
				projectType: this.params.projectType,
				inspectionName: this.params.inspectionName
			}).then(response => {
				downloadBlob(response.data, name);
			});
		},
		//获取左侧列表
		getInspectionItems() {
			getInspectionItems()
				.then(res => {
					this.treeList = res.data.data;
					let num = this.treeList.length - 1;
					this.treeList.forEach((e, i) => {
						this.$set(this.treeList[i], "id", i + 1);
						e.children.forEach((q, w) => {
							num++;
							this.$set(this.treeList[i].children[w], "id", num + 1);
						});
						this.propertyTypes.forEach((v, index) => {
							if (Object.is(e.projectType, v.value)) {
								this.treeList[i].label = v.label;
							}
						});
					});
				})
				.catch(() => {});
		},
		// 获取右侧列表
		getListData(params = {}) {
			let requestData = { ...this.params, ...params };
			getInspectionMethod(requestData)
				.then(res => {
					const { current, size, total, records } = res.data.data;
					this.tableData = records;
					this.params = requestData;
					this.pager = { total, current, size };
				})
				.catch(() => {});
		},
		// 物业项选择改变
		handleNodeClick(data, e, b) {
			this.params = {};
			this.form.inspectionId = e.data.inspectionId;
			if (data.projectType) {
				this.form.inspectionName = "";
				this.form.projectType = data.projectType;
				this.params.projectType = data.projectType;
			} else {
				this.form.projectType = e.parent.data.projectType;
				this.form.inspectionName = data.label;
				this.params.inspectionId = data.inspectionId;
				this.params.projectType = e.parent.data.projectType;
			}
			this.getListData();
		},
		//打开 新增/编辑/查看   弹框  事件
		showAddOrEdit(v, row) {
			this.restaurants = [];
			// 弹框控制
			this.dialogVisible = true;
			// 设置 新增/编辑/查看  弹框title
			switch (v) {
				case "add":
					this.title = "新增检查方法";
					if (this.form.projectType) this.getTinspectionName();
					break;
				case "edit":
					this.title = "编辑检查方法";
					this.form = JSON.parse(JSON.stringify(row));
					break;
			}
		},
		// 展示检查项的全部列表(用于模糊搜索)
		async getTinspectionName() {
			let rps = await getTinspectionName(this.form.projectType);
			this.restaurants = JSON.parse(JSON.stringify(rps.data.data));
			if (this.restaurants.length == 0) return (this.form.inspectionName = "");
			let result = this.restaurants.some((item, index) => {
				return item.value == this.form.inspectionName;
			});
			if (!result) this.form.inspectionName = "";
		},
		// 保存
		preservation(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					if (this.title == "新增检查方法") {
						// 如果是新增
						addInspectionMethod(this.form).then(response => {
							if (response.data.data.data == 500) {
								return this.$message.warning(response.data.data.msg);
							}
							this.$message.success(response.data.data.msg);
							this.dialogVisible = false;
							this.getListData();
							this.getInspectionItems();
						});
					} else {
						//如果是编辑
						editInspectionMethod(this.form).then(response => {
							if (response.data.data.data == 500) {
								return this.$message.warning(response.data.data.msg);
							}
							this.$message({
								message: response.data.data.msg,
								type: "success"
							});
							this.dialogVisible = false;
							this.getListData();
							this.getTinspectionName();
							this.getInspectionItems();
						});
					}
				} else {
					return false;
				}
			});
		},
		// 删除 检查方法
		handleDelete() {
			if (!this.selectDataArr.length) {
				return this.$alert("请勾选要删除的数据！");
			}
			let ids = this.selectDataArr.map(e => e.wayId);
			this.$confirm(`此操作将永久删除该数据, 是否继续?`, {
				type: "warning"
			})
				.then(() => {
					delInspectionMethod(ids)
						.then(res => {
							this.getListData();
							this.getTinspectionName();
							this.getInspectionItems();
							this.$message.success("删除成功");
						})
						.catch(e => {
							this.$message.error("删除失败");
						});
				})
				.catch(() => {
					this.$message.info("已取消删除");
				});
		}
	}
};
